/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadastroAluno.java
 *
 * Created on 17/06/2011, 14:33:38
 */
package cadastros;

import utilitarios.ConnectionHelper;
import visao.Telaprincipal;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import dao.DaoAluno;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import pojo.Aluno;

/**
 *
 * @author Jean
 */
public class CadastroAluno extends javax.swing.JFrame {
    int navega =0;
    
    private Connection conn = null;
    private PreparedStatement pstm;
    private ResultSet rs;
    DaoAluno daoAluno;
    Aluno aluno;

    /** Creates new form CadastroAluno */
    public CadastroAluno(Telaprincipal t) {
        initComponents();
        conn = ConnectionHelper.getIntance().getConnection();
                
      //  con_matricula = new ConnectionHelper();
      //  con_matricula.conecta();
      try{  
        pstm = conn.prepareStatement("select * from aluno");
        pstm.execute();
        rs = pstm.getGeneratedKeys();
        this.setLocationRelativeTo(t);
        if(rs.next()){
                rs.first();
                td_codigo.setText(Long.toString(rs.getLong(1)));
                td_nome.setText(rs.getString(2));
                td_idade.setText(Integer.toString(rs.getInt(3)));
                td_cpf.setText(rs.getString(4));
            
        }
        }catch(SQLException erro){
            JOptionPane.showMessageDialog(null,"Não localizou dados"+erro);
    }
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        td_nome = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        td_codigo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        td_idade = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        td_cpf = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        bt_primeiro = new javax.swing.JButton();
        bt_anterior = new javax.swing.JButton();
        bt_proximo = new javax.swing.JButton();
        bt_ultimo = new javax.swing.JButton();
        bt_novo = new javax.swing.JButton();
        bt_gravar = new javax.swing.JButton();
        bt_excluir = new javax.swing.JButton();
        bt_alterar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nome");

        jLabel2.setText("Código");

        jLabel3.setText("Idade");

        jLabel4.setText("CPF");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel6.setText("Cadastro de Alunos");

        bt_primeiro.setText("<<");
        bt_primeiro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_primeiroActionPerformed(evt);
            }
        });

        bt_anterior.setText("<");
        bt_anterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_anteriorActionPerformed(evt);
            }
        });

        bt_proximo.setText(">");
        bt_proximo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_proximoActionPerformed(evt);
            }
        });

        bt_ultimo.setText(">>");
        bt_ultimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_ultimoActionPerformed(evt);
            }
        });

        bt_novo.setText("Novo");
        bt_novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_novoActionPerformed(evt);
            }
        });

        bt_gravar.setText("Gravar");
        bt_gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_gravarActionPerformed(evt);
            }
        });

        bt_excluir.setText("Excluir");
        bt_excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_excluirActionPerformed(evt);
            }
        });

        bt_alterar.setText("Alterar");
        bt_alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_alterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(td_idade, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(td_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 200, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(td_codigo, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(td_nome))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel4)
                                        .addGap(0, 0, Short.MAX_VALUE))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(91, 91, 91)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(bt_primeiro)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_anterior)
                        .addGap(18, 18, 18)
                        .addComponent(bt_proximo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_ultimo))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(bt_novo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_gravar)
                        .addGap(18, 18, 18)
                        .addComponent(bt_excluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_alterar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(td_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(td_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(td_idade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(td_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_primeiro)
                    .addComponent(bt_anterior)
                    .addComponent(bt_proximo)
                    .addComponent(bt_ultimo))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_novo)
                    .addComponent(bt_gravar)
                    .addComponent(bt_excluir)
                    .addComponent(bt_alterar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bt_novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_novoActionPerformed
        // TODO add your handling code here:
        td_codigo.setText("");
        td_nome.setText("");
        td_idade.setText("");
        td_cpf.setText("");
        td_codigo.setEditable(false);
        
    }//GEN-LAST:event_bt_novoActionPerformed

    private void bt_gravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_gravarActionPerformed
        // TODO add your handling code here:
        try
        {
            aluno.setNome(td_nome.getText());
            aluno.setIdade(Integer.parseInt(td_idade.getText()));
            aluno.setCpf(td_cpf.getText());
            daoAluno.commit(aluno);
            
            JOptionPane.showMessageDialog(null, "Gravação realizada com sucesso");
            
            pstm = conn.prepareStatement("select * from aluno");
            rs = pstm.getGeneratedKeys();
            rs.next();
            mostra_dados();
        }catch(SQLException sqlex){
            JOptionPane.showMessageDialog(null,"Não foi possível gravar dados; erro: "+sqlex);
        }
    }//GEN-LAST:event_bt_gravarActionPerformed

    private void bt_proximoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_proximoActionPerformed
        // TODO add your handling code here:
         try{
            rs.next();
            mostra_dados();
            navega=2;
        }catch(SQLException erro){
        JOptionPane.showMessageDialog(null,"Não foi possível ir para o primeiro registro"+erro);
        }
    }//GEN-LAST:event_bt_proximoActionPerformed

    private void bt_primeiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_primeiroActionPerformed
        // TODO add your handling code here:
       try{
            rs.first();
            mostra_dados();
        }catch(SQLException erro){
            JOptionPane.showMessageDialog(null,"Não foi possível ir para o primeiro registro"+erro);
        }
    }//GEN-LAST:event_bt_primeiroActionPerformed

    private void bt_anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_anteriorActionPerformed
        // TODO add your handling code here:
       try{
            rs.previous();
            mostra_dados();
            navega=1;
        }catch(SQLException erro){
            JOptionPane.showMessageDialog(null,"Não foi possível ir para o primeiro registro"+erro);
        }
    }//GEN-LAST:event_bt_anteriorActionPerformed

    private void bt_ultimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_ultimoActionPerformed
        // TODO add your handling code here:
        try{
            rs.last();
            mostra_dados();
        }catch(SQLException erro){
            JOptionPane.showMessageDialog(null,"Não foi possível ir para o primeiro registro"+erro);
        }
    }//GEN-LAST:event_bt_ultimoActionPerformed

    private void bt_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_excluirActionPerformed
        // TODO add your handling code here:
            int id = Integer.parseInt(td_codigo.getText());
            daoAluno.delete(id);
                 
    }//GEN-LAST:event_bt_excluirActionPerformed

    private void bt_alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_alterarActionPerformed
        // TODO add your handling code here:
        try
        {
            aluno = new Aluno();
            aluno.setId(Long.parseLong(td_codigo.getText()));
            aluno.setNome(td_nome.getText());
            aluno.setIdade(Integer.parseInt(td_idade.getText()));
            aluno.setCpf(td_cpf.getText());
            
            daoAluno.update(aluno);
        }
        catch(SQLException erro)
        {
            JOptionPane.showMessageDialog(null,"Erro ao tentar alterar o registro..."+erro);
        }
    }//GEN-LAST:event_bt_alterarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
               // new CadastroAluno().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_alterar;
    private javax.swing.JButton bt_anterior;
    private javax.swing.JButton bt_excluir;
    private javax.swing.JButton bt_gravar;
    private javax.swing.JButton bt_novo;
    private javax.swing.JButton bt_primeiro;
    private javax.swing.JButton bt_proximo;
    private javax.swing.JButton bt_ultimo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField td_codigo;
    private javax.swing.JTextField td_cpf;
    private javax.swing.JTextField td_idade;
    private javax.swing.JTextField td_nome;
    // End of variables declaration//GEN-END:variables
 public void mostra_dados(){
         try{
            td_codigo.setText(rs.getString("al_id"));
            td_nome.setText(rs.getString("al_nome"));
            td_idade.setText(rs.getString("al_idade"));
            td_cpf.setText(rs.getString("al_cpf"));
            
            
        }
        catch(SQLException erro)
        {
            if (navega == 1)
                JOptionPane.showMessageDialog(null,"voce já está no primeiro Registro");
            else if (navega ==2)
                JOptionPane.showMessageDialog(null,"voce já está no ultimo Registro");
            else
                JOptionPane.showMessageDialog(null,"Não localizou dados"+erro);
            navega=0;
        }
    }


}
